import socket
import os
from cryptography.fernet import Fernet

# 创建 socket 对象
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# 绑定地址和端口
server_address = ('172.16.219.51', 9999)
server_socket.bind(server_address)

# 监听连接
server_socket.listen(1)
print('服务器正在监听 {}:{}'.format(*server_address))

try:
    # 接受客户端连接
    client_socket, client_address = server_socket.accept()
    print('接受来自 {} 的连接'.format(client_address))

    # 接收密钥
    key = client_socket.recv(1024)
    cipher_suite = Fernet(key)
    print("接收到密钥")

    # 接收文件路径
    file_path = client_socket.recv(1024).decode('utf-8')
    print(f"接收到文件路径：{file_path}")

    # 接收文件大小
    file_size = int(client_socket.recv(1024).decode('utf-8'))
    print(f"接收到文件大小：{file_size} 字节")

    # 发送确认信息
    confirmation_message = "准备好接收文件"
    client_socket.send(confirmation_message.encode('utf-8'))  # 使用 encode() 方法将字符串转换为字节
    print("发送确认信息：准备好接收文件")

    # 接收文件数据
    received_size = 0
    with open('received_file.enc', 'wb') as file:
        while received_size < file_size:
            data = client_socket.recv(1024)
            if not data:
                break
            file.write(data)
            received_size += len(data)
            print(f"已接收 {received_size} 字节")

    print("文件接收完成")

finally:
    # 关闭连接
    client_socket.close()
    server_socket.close()